﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SharpObjects.SearchEngine.HtmlParsing.Html
{

    public abstract class HtmlTag
    {
        public List<HtmlAttribute> Attributes = new List<HtmlAttribute>();
        public abstract string Name { get; set; }
        public virtual string Text { get; set; }
        public virtual bool IsClosed { get; set; }
        public bool IsClosing { get; set; }
        public virtual bool IsContent { get; set; }
        public virtual bool IsInline { get; set; }
        public virtual double IndexingBoost { get; set; }
        public virtual bool IsContainer { get; set; }
        public virtual bool HasText { get; set; }

        public HtmlTag(HtmlTag tag = null)
        {
            this.IndexingBoost = 1.0;
            this.IsContainer = false;
            this.HasText = false;

            if (tag == null)
            {
                this.IsClosed = false;
                this.IsClosing = false;
                this.Text = string.Empty;
            }
            else
            {
                this.IsClosed = tag.IsClosed;
                this.IsClosing = tag.IsClosing;
                this.Attributes = tag.Attributes;
                this.Text = tag.Text;
            }
        }

        public void AddAttribute(HtmlAttribute attribute)
        {
            this.Attributes.Add(attribute);
        }

        public void SetAttribute(string name, string value)
        {
            name = name.ToLower();

            if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(value))
            {
                HtmlAttribute attribute = GetAttribute(name);

                if (attribute == null)
                {
                    attribute = new HtmlAttribute() { Name = name, Value = value };
                    this.AddAttribute(attribute);
                }
                else
                {
                    attribute.Value = value;
                }
            }
        }


        public HtmlAttribute GetAttribute(string name)
        {
            name = name.ToLower();

            var foundAttribute =
                (from attribute in this.Attributes
                 where attribute.Name == name
                 select attribute).FirstOrDefault();

            if(foundAttribute == null)
            {
                return new HtmlAttribute() {Name = name, Value = string.Empty};
            }
            else
            {
                return foundAttribute;
            }
        }

        public override string ToString()
        {
            string display = string.Format("{0}: {1}\n", this.Name, this.Text);
            return display;
        }
    }
}